package com.mall.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.db.domain.Member;
import com.mall.db.domain.SendMessage;
import com.mall.db.service.MemberService;
import com.mall.db.service.SendMessageService;
import com.mall.utils.SmsUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Component
public class SendMsmJob implements BaseJob {

    @Resource(name = "sendMessageService")
    private SendMessageService sms;
    @Resource(name = "memberService")
    private MemberService ms;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //查询未发送的短信
        QueryWrapper<SendMessage> qw = new QueryWrapper<>();
        qw.eq("type", "sms").eq("state", "1");
        List<SendMessage> list = sms.list(qw);
        Calendar c = Calendar.getInstance();
        for (SendMessage sm : list) {
            //获取被发送的手机号码
            QueryWrapper<Member> qm = new QueryWrapper<>();
            qm.eq("login_name", sm.getAcceptUsers());
            Member m = ms.getOne(qm);
            try {
                if (!StringUtils.isEmpty(m.getMobile())) {
                    List<String> mobile = new ArrayList<>();
                    mobile.add(m.getMobile());
                    String data[] = {sm.getContent(), "5"};//TODO 短信模板默认为1
                    List<Map<String, Object>> result = SmsUtil.sendSmsToMobile(mobile, "1", data);
                    for (Map<String, Object> map : result) {
                        sm.setState((boolean) map.get("is") ? 0 : 1);
                        c.setTimeInMillis((long) map.get("time"));
                        sm.setSendTime(c.getTime());
                        sms.updateById(sm);
                    }
                }

            } catch (Exception e) {
                System.out.println("定时任务" + m.getMobile() + "短信发送异常" + e.getMessage());
            }
        }
    }
}
